const { SportRecord, DietRecord, WeightRecord, SleepRecord, User } = require('../models');
const { Op } = require('sequelize');

const recordController = {
  // 添加运动记录
  async addSportRecord(req, res) {
    try {
      const userId = req.user.id;
      const { type, duration, distance, calories, notes, date } = req.body;

      const record = await SportRecord.create({
        userId,
        type,
        duration,
        distance,
        calories,
        notes,
        date
      });

      res.status(201).json(record);
    } catch (error) {
      console.error('添加运动记录失败:', error);
      res.status(400).json({ error: error.message || '添加运动记录失败' });
    }
  },

  // 获取用户的运动记录
  async getSportRecords(req, res) {
    try {
      const userId = req.user.id;
      const { startDate, endDate, page = 1, pageSize = 10 } = req.query;

      const where = { userId };
      if (startDate && endDate) {
        where.date = {
          [Op.between]: [startDate, endDate]
        };
      }

      const offset = (page - 1) * pageSize;

      const records = await SportRecord.findAll({
        where,
        order: [['date', 'DESC'], ['createdAt', 'DESC']],
        limit: parseInt(pageSize),
        offset: parseInt(offset)
      });

      res.json({
        records,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      });
    } catch (error) {
      console.error('获取运动记录失败:', error);
      res.status(400).json({ error: error.message || '获取运动记录失败' });
    }
  },

  // 获取今日运动记录
  async getTodayRecords(req, res) {
    try {
      const userId = req.user.id;
      const today = new Date().toISOString().split('T')[0];

      // 获取今日运动记录
      const sportRecords = await SportRecord.findAll({
        where: {
          userId,
          date: today
        }
      });

      // 获取今日饮食记录
      const dietRecords = await DietRecord.findAll({
        where: {
          userId,
          date: today
        }
      });

      // 获取今日最新体重记录
      const weightRecord = await WeightRecord.findOne({
        where: {
          userId,
          date: today
        },
        order: [['createdAt', 'DESC']]
      });

      // 获取今日睡眠记录
      const sleepRecord = await SleepRecord.findOne({
        where: {
          userId,
          date: today
        }
      });

      // 计算今日运动消耗的总热量
      const sportCalories = sportRecords.reduce((total, record) => {
        return total + (record.calories || 0);
      }, 0);

      // 计算今日饮食摄入的总热量
      const mealCalories = dietRecords.reduce((total, record) => {
        return total + (record.totalCalories || 0);
      }, 0);

      res.json({
        sportCalories,
        mealCalories,
        sportRecords,
        dietRecords,
        weight: weightRecord ? weightRecord.weight : null,
        sleep: sleepRecord
      });
    } catch (error) {
      console.error('获取今日记录失败:', error);
      res.status(400).json({ error: error.message || '获取今日记录失败' });
    }
  },

  // 添加饮食记录
  async addDietRecord(req, res) {
    try {
      const userId = req.user.id;
      const {
        mealType,
        foods,
        totalCalories,
        totalProtein,
        totalCarbs,
        totalFat,
        notes,
        images,
        date
      } = req.body;

      const record = await DietRecord.create({
        userId,
        mealType,
        foods,
        totalCalories,
        totalProtein,
        totalCarbs,
        totalFat,
        notes,
        images,
        date
      });

      res.status(201).json(record);
    } catch (error) {
      console.error('添加饮食记录失败:', error);
      res.status(400).json({ error: error.message || '添加饮食记录失败' });
    }
  },

  // 获取用户的饮食记录
  async getDietRecords(req, res) {
    try {
      const userId = req.user.id;
      const { startDate, endDate, page = 1, pageSize = 10 } = req.query;

      const where = { userId };
      if (startDate && endDate) {
        where.date = {
          [Op.between]: [startDate, endDate]
        };
      }

      const offset = (page - 1) * pageSize;

      const records = await DietRecord.findAll({
        where,
        order: [['date', 'DESC'], ['createdAt', 'DESC']],
        limit: parseInt(pageSize),
        offset: parseInt(offset)
      });

      res.json({
        records,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      });
    } catch (error) {
      console.error('获取饮食记录失败:', error);
      res.status(400).json({ error: error.message || '获取饮食记录失败' });
    }
  },

  // 添加体重记录
  async addWeightRecord(req, res) {
    try {
      const { date, weight, notes } = req.body;
      const userId = req.user.id;

      const record = await WeightRecord.create({
        userId,
        date,
        weight,
        notes
      });

      // 更新用户的当前体重
      await User.update(
        { weight },
        { where: { id: userId } }
      );

      res.status(201).json(record);
    } catch (error) {
      console.error('添加体重记录失败:', error);
      res.status(400).json({
        error: error.message || '添加体重记录失败'
      });
    }
  },

  // 获取体重记录列表
  async getWeightRecords(req, res) {
    try {
      const userId = req.user.id;
      const { page = 1, pageSize = 20 } = req.query;
      const offset = (page - 1) * pageSize;

      const records = await WeightRecord.findAll({
        where: { userId },
        order: [['id', 'DESC']],
        limit: parseInt(pageSize),
        offset: parseInt(offset)
      });

      res.json({
        records: records.map(record => ({
          id: record.id,
          date: record.date,
          weight: record.weight,
          notes: record.notes
        }))
      });
    } catch (error) {
      console.error('获取体重记录失败:', error);
      res.status(400).json({
        error: error.message || '获取体重记录失败'
      });
    }
  },

  // 添加睡眠记录
  async addSleepRecord(req, res) {
    try {
      const userId = req.user.id;
      const { date, startTime, endTime, duration, quality, notes } = req.body;

      const record = await SleepRecord.create({
        userId,
        date,
        startTime,
        endTime,
        duration,
        quality,
        notes
      });

      res.status(201).json(record);
    } catch (error) {
      console.error('添加睡眠记录失败:', error);
      res.status(400).json({
        error: error.message || '添加睡眠记录失败'
      });
    }
  },

  // 获取睡眠记录列表
  async getSleepRecords(req, res) {
    try {
      const userId = req.user.id;
      const { startDate, endDate, page = 1, pageSize = 20 } = req.query;

      const where = { userId };
      if (startDate && endDate) {
        where.date = {
          [Op.between]: [startDate, endDate]
        };
      }

      const offset = (page - 1) * pageSize;

      const records = await SleepRecord.findAll({
        where,
        order: [['date', 'DESC'], ['createdAt', 'DESC']],
        limit: parseInt(pageSize),
        offset: parseInt(offset)
      });

      res.json({
        records,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      });
    } catch (error) {
      console.error('获取睡眠记录失败:', error);
      res.status(400).json({
        error: error.message || '获取睡眠记录失败'
      });
    }
  },

  // 获取今日营养摄入
  async getTodayNutrition(req, res) {
    try {
      const userId = req.user.id;
      const today = new Date().toISOString().split('T')[0];

      // 获取今日所有饮食记录
      const dietRecords = await DietRecord.findAll({
        where: {
          userId,
          date: today
        }
      });

      // 计算总营养摄入
      const nutrition = dietRecords.reduce((total, record) => {
        return {
          calories: total.calories + (record.totalCalories || 0),
          protein: total.protein + (record.totalProtein || 0),
          carbs: total.carbs + (record.totalCarbs || 0),
          fat: total.fat + (record.totalFat || 0)
        };
      }, {
        calories: 0,
        protein: 0,
        carbs: 0,
        fat: 0
      });

      res.json(nutrition);
    } catch (error) {
      console.error('获取今日营养摄入失败:', error);
      res.status(500).json({
        error: '获取今日营养摄入失败'
      });
    }
  }
};

module.exports = recordController; 